<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- import CSS -->
<link rel="stylesheet" href="/css/elementui/index.css">
<link rel="stylesheet" href="/css/exam/css/style.css">
<link rel="stylesheet" href="/iconfont/iconfont.css">
</head>
<body>
<div id="app">
  <div  class="p-30">
    <el-row>
	
      <span class="icon iconfont icon-arrow_back"></span> <a :href="'/admin/examview/question?id=' + id">返  回</a> | 添加试题
    </el-row><br>
    <el-row type="flex" class="row-bg" justify="space-between">
      <el-row>
        <el-button type="primary" @click="addmulti"><span style="display:block;color:#fff;text-decoration:none">批量添加</span></el-button>
      </el-row>
    </el-row>

<br>
<h5>已选择<span>@{{ total }}</span>项</h5>
<template>
    <el-table  ref="multipleTable" :data="examList" :row-key="(row) => row.id"  border  style="width: 100%" @selection-change="handleSelectionChange" >  
          <el-table-column type="selection" width="50" :reserve-selection="true"> </el-table-column>
          <el-table-column  prop="id"  label="试题ID"  width="70">   </el-table-column>
          <el-table-column  prop="category.c_name"  label="分&ensp;&ensp;类"  width="200"> </el-table-column>
          <el-table-column prop="difficulty" label="难&ensp;&ensp;度"  sortable width="100">
              <template slot-scope="scope">
                <el-tag type="primary" v-if="scope.row.difficulty === 1">简单</el-tag>
                <el-tag type="primary" v-else-if="scope.row.difficulty === 2"
                  >中等</el-tag
                >
                <el-tag type="primary" v-else-if="scope.row.difficulty === 3"
                  >难</el-tag
                >
                <el-tag type="primary" v-else-if="scope.row.difficulty === 4"
                  >特别难</el-tag
                >
              </template>
          </el-table-column>
          <el-table-column  prop="score"  label="分&ensp;&ensp;数"  width="200">   </el-table-column>
          <el-table-column  prop="exam_content"  label="内&ensp;&ensp;容"  width="">   </el-table-column>
    </el-table>
  </template>

    <template>
        <!-- 分页组件 -->
        <div class="block" style="margin-top:15px;">
            <el-pagination align='center' @size-change="handleSizeChange" @current-change="handleCurrentChange" 
            :current-page="currentPage" 
            :page-sizes="[10,20,50,100]" 
            :page-size="pageSize" 
            layout="total, sizes, prev, pager, next, jumper" 
            :total="count">
            </el-pagination>
        </div>

    </template>


  </div>

</div>
</body>
<script src="/css/exam/js/vue.js"></script>
<script src="/css/elementui/index.js"></script>
<script src="/css/exam/js/axios.min.js"></script>
<script>

const app = new Vue({
  el: '#app',
  data() {
    return {  
       id:'',
       ids:[],
	   pid:'',
       loading:false,   
       examList: [], //试题列表
	   examData:[],//组卷数据
       currentPage: 1, // 当前页码
       count: 20, // 总条数
       pageSize: 10,// 每页的数据条数
       total:0,
	   multipleSelection: [],//选中的列表
        arr:[
          1,3,5
        ]
    }
  },
  created() {
       this.getUrlKey()
       this.getexamlist()
	   this.getquestiondata()
	  

  },

  methods: {

          //获取当前浏览器地址url中的id
          getUrlKey() {
            var url = window.location.href ;             //获取当前url
            var dz_url = url.split('#')[0];              //获取#/之前的字符串
            var cs = dz_url.split('?')[1];               //获取?之后的参数字符串
            var cs_arr = cs.split('&');                  //参数字符串分割为数组
            var cs={};
            for(var i=0;i<cs_arr.length;i++){         //遍历数组，拿到json对象
              cs[cs_arr[i].split('=')[0]] = cs_arr[i].split('=')[1]
            }
            this.id = cs.id;
            console.log("this.id:"+this.id);
            }, 
 
			// 获取列表
			async getquestiondata() {   
				console.log('select1==');
			   let pid = this.id;   
			   await axios.post('/admin/paper/questions_index',{pid:pid})
			   .then(response =>{
				   this.examData = response.data.data.exam;
				   console.log(this.examData,'---');
			   }).catch(error =>{
				   console.log('请求失败：' + error);
			   })
			 },
			 // 获取试题列表
			  async getexamlist() { 
			   this.loading = true;   
			   await this.getquestiondata()
			   await axios.post('/admin/exam/index',{limit: this.pageSize, page: this.currentPage})
			   .then(response =>{
			       console.log('请求成功：',response.data.data);
			       this.examList = response.data.data;
			       this.count = response.data.count;
			       this.loading = false;				   
			 	   this.selectok()
			   }).catch(error =>{
			       console.log('请求失败：' + error);
			       this.loading = false;
			   })
			 },

          //回显选中
		  selectok() {
			  this.$nextTick(() => {
		  		  this.examList.forEach(row =>{
		  		  	this.examData.forEach(item2 =>{
		  		  		if(row.id == item2.id){
		  					console.log(row.id);
		  		  			 this.$refs.multipleTable.toggleRowSelection(row,true);
		  		  		}
		  		  	})
		  		  })
			  })
		  },
        toggleSelection(rows) {
          if (rows) {
            rows.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row);
            });
          } else {
            this.$refs.multipleTable.clearSelection();
          }
        },

          handleSelectionChange(val) {
			    this.multipleSelection = val;
                console.log('var',this.multipleSelection);
                let newbox = [];
                let num = 0;
                for (var i = 0; i < val.length; i++) {
                  newbox.push(val[i].id);
                  num = num + 1;
                }
                this.ids = newbox;
                this.total = num;
              },

           // 批量添加
           addmulti() {
              if (this.ids == "") {
                this.$message.error("请选择需要添加的数据");
                return;
              }
              this.$confirm("确认操作？", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  //点击确定按钮的操作
                  if (this.loading) {
                    return;
                  }
                  this.loading = true;
                  let ids = this.ids.join(',')  
                  let id = this.id                 
                    axios.post('/admin/paper/questions_add',{pid:id,eid:ids})
                    .then(() => {
                      this.loading = false;
					  window.location=document.referrer;
                     this.$message({
                         type: 'success',
                         message: '保存成功！'
                     });
                    }) .catch(error =>{
                      this.$message.info("添加失败！");
                    })
                })
                .catch(() => {
                  this.$message.info("添加失败！");
                });
            },
          //分类列表        
          getciddata() {           
            axios.get('/admin/paper/category_index')
            .then(response =>{
                this.cidData = response.data.data;  
                console.log('...' + response.data.data);             
            }).catch(error =>{
                console.log('请求失败：' + error);
            })
          }, 
          // 分页页码  
          handleSizeChange(val){
            console.log(`每页 ${val} 条`);
				    this.currentPage = 1;
				    this.pageSize = val;
            this.getexamlist()
          },
          handleCurrentChange(val){
            console.log(`当前页: ${val}`);
				    this.currentPage = val;
					  this.getexamlist()
          },

        },       

   }) 
</script>
<style scoped>
  .el-table .el-table__cell:first-child{text-align: center;}
   a{color:#409EFF;text-decoration: none;}
</style>
</html>

